package com.dhcc.bpm.common.utils.http;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName HttpsUtils
 * @Description TODO
 * @Author wangjinghan
 * @Date 2020/1/7 17:20
 * @Version 1.0
 */


@SuppressWarnings("deprecation")
public class HttpsUtils
{
    private static Logger logger = LoggerFactory.getLogger(HttpsUtils.class);

    /**
     * 向HTTPS地址发送POST请求
     * @param reqURL 请求地址
     * @param params 请求参数
     * @return 响应内容
     */
    @SuppressWarnings({ "finally", "resource" })
    public static String sendSSLPostRequest(String reqURL, Map<String, String> params)
    {
        long responseLength = 0;                         //响应长度
        String responseContent = null;                   //响应内容
        try
        {
            HttpClient httpClient = HttpClientFactory.getHttpsClient();
            HttpPost httpPost = new HttpPost(reqURL);                        //创建HttpPost
            List<NameValuePair> formParams = new ArrayList<NameValuePair>(); //构建POST请求的表单参数
            if(params != null)
            {
                for(Map.Entry<String,String> entry : params.entrySet()){
                    formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));

            HttpResponse response = httpClient.execute(httpPost); //执行POST请求
            HttpEntity entity = response.getEntity();             //获取响应实体

            if (null != entity) {
                responseLength = entity.getContentLength();
                responseContent = EntityUtils.toString(entity, "UTF-8");
                EntityUtils.consume(entity); //Consume response content
            }
            logger.info("请求地址: " + httpPost.getURI());
            logger.info("响应状态: " + response.getStatusLine());
            logger.info("响应长度: " + responseLength);
            logger.info("响应内容: " + responseContent);
            httpClient.getConnectionManager().shutdown(); //关闭连接,释放资源
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            return responseContent;
        }
    }

    @SuppressWarnings({ "finally", "resource" })
    public static String sendSSLPostBodyRequest(String reqURL, String bodyStr)
    {
        long responseLength = 0;                         //响应长度
        String responseContent = null;                   //响应内容

        try
        {
            HttpClient httpClient = HttpClientFactory.getHttpsClient();
            //创建HttpPost
            HttpPost httpPost = new HttpPost(reqURL);
            if(!StringUtils.isBlank(bodyStr))
            {
                HttpEntity requestEntity = new StringEntity(bodyStr, "UTF-8");
                httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
                httpPost.setEntity(requestEntity);
            }
            // 创建请求内容
           // StringEntity entity = new StringEntity(bodyStr, "application/json");
           // httpPost.setEntity(entity);
            //执行POST请求
            HttpResponse response = httpClient.execute(httpPost);
            //获取响应实体
            HttpEntity entity = response.getEntity();

            if (null != entity) {
                responseLength = entity.getContentLength();
                responseContent = EntityUtils.toString(entity, "UTF-8");
                //Consume response content
                EntityUtils.consume(entity);
            }
            logger.info("请求地址: " + httpPost.getURI());
            logger.info("响应状态: " + response.getStatusLine());
            logger.info("响应长度: " + responseLength);
            logger.info("响应内容: " + responseContent);
            httpClient.getConnectionManager().shutdown(); //关闭连接,释放资源
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            return responseContent;
        }
    }

    /**
     * 向HTTPS地址发送GET请求
     * @param reqURL 请求地址
     * @param params 请求参数
     * @return 响应内容
     */
    @SuppressWarnings({ "finally", "resource" })
    public static String sendSSLGetRequest(String reqURL, Map<String, String> params)
    {
        long responseLength = 0;                         //响应长度
        String responseContent = null;                   //响应内容
        try
        {
            HttpClient httpClient = HttpClientFactory.getHttpsClient();
            HttpGet httpGet = new HttpGet();                        //创建HttpPost
            List<NameValuePair> formParams = new ArrayList<NameValuePair>(); //构建POST请求的表单参数
            if(params != null)
            {
                for(Map.Entry<String,String> entry : params.entrySet()){
                    formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            String param = formParams.toString();
            httpGet.setURI(new URI(reqURL + "?" + param.substring(1,param.length()).replaceAll(", ","&")));
            try {
                HttpResponse response = httpClient.execute(httpGet);
                int statusCode = response.getStatusLine().getStatusCode();

                logger.info("执行状态码 : " + statusCode);

                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    InputStream instream = entity.getContent();
                    responseContent = IOUtils.toString(instream, "UTF-8");
                }
                logger.info("请求地址: " + httpGet.getURI());
                logger.info("响应状态: " + response.getStatusLine());
                logger.info("响应长度: " + responseLength);
                logger.info("响应内容: " + responseContent);
                httpClient.getConnectionManager().shutdown(); //关闭连接,释放资源
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            return responseContent;
        }
    }

}